<script setup>
import { ref, onMounted } from 'vue'
import { ElCarousel, ElCarouselItem, ElCard, ElRow, ElCol, ElButton, ElMenu, ElMenuItem, ElInput, ElIcon, ElMessage } from 'element-plus'
import { Search, ShoppingCart, User, Star, Present, Timer } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { useTokenStore } from '@/stores/token.js'
import useUserInfoStore from '@/stores/userInfo.js'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import {getAdvertiseService,getHomeProductService,getParentCategoryService} from '@/api/product.js'
// 导入广告图片
import AD1 from '@/assets/AD/AD_1.jpg'
import AD2 from '@/assets/AD/AD_2.jpg'
import AD3 from '@/assets/AD/AD_3.jpg'
import AD4 from '@/assets/AD/AD_4.jpg'
import AD5 from '@/assets/AD/AD_5.png'
import AD6 from '@/assets/AD/AD_6.jpg'
import AD7 from '@/assets/AD/AD_7.jpg'
import AD8 from '@/assets/AD/AD_8.jpg'


const router = useRouter()
const cartStore = useCartStore()
const tokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()

// 分类
const categories = ref([])
// 获取分类数据
const getCategories = async () => {
  try {
    const result = await getParentCategoryService()
    categories.value = result.data
  } catch (error) {
    console.error('Failed to fetch categories:', error)
  }
}
// 猜你喜欢
const mightLikeProducts = ref()
// 热销商品
const featuredProducts = ref()
// 新品上市
const newProducts = ref()
// 广告数据
const advertisements = ref()
// 导航方法
const navigateToCategory = (url) => {
  let baseUrl = '/home/category/'
  router.push(baseUrl + url)
}
// 跳转到商品详情页
const navigateToProduct = (productId) => {
  router.push(`/home/product/${productId}`)
}
// 跳转到购物车
const navigateToCart = () => {
  if (!tokenStore.token) {
    ElMessage.error('请先登录再加入购物车')
    router.push('/login')
    return
  }
  router.push('/home/cart')
}
// 查看更多
const navigateToMore = (type) => {
  router.push(`/home/category/${type}`)
}
// 加入购物车
const handleAddToCart = (product) => {
  if (!tokenStore.token) {
    ElMessage.error('请先登录再加入购物车')
    router.push('/login')
    return
  }
  cartStore.addToCart(product)
  console.log('已添加至购物车（来自首页）:', product.name)
  console.log("商品内容",product)
  ElMessage.success('已加入购物车')
}

// 获取广告数据
const getAdvertiseAndProducts = async () => { 
 let result = await getAdvertiseService()
 advertisements.value = result.data
}
// 获取首页商品数据
const getHomeProducts = async (type,isHome) => { 
  let result = await getHomeProductService(type,isHome)
  let data = result.data
  
  // 随机打乱数组
  const shuffleArray = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }

  if(type === 0){
    // 猜你喜欢 - 随机4个
    mightLikeProducts.value = shuffleArray([...data]).slice(0, 4)
  }
  if(type === 1){
    // 精选商品 - 随机8个
    featuredProducts.value = shuffleArray([...data]).slice(0, 8)
  }
  if(type === 2){
    // 新品上市 - 随机4个
    newProducts.value = shuffleArray([...data]).slice(0, 4)
  }
}

// 当页面加载时获取广告数据
onMounted(() => {
  console.log('首页挂载')
  getAdvertiseAndProducts()

  let isHome = true
  getHomeProducts(0,isHome)
  getHomeProducts(1,isHome)
  getHomeProducts(2,isHome)
  getCategories()
})

</script>

<template>
  <!-- 导航栏 -->
  <CommonHeader />
  <!-- 侧边栏 -->
  <FloatingSidebar />
  <div class="home-container">

    <!-- 广告展示区 -->
    <div class="ad-section">
      <el-carousel 
        :interval="4000" 
        type="card" 
        height="300px"
        :autoplay="true"
        indicator-position="outside"
        arrow="always"
      >
        <el-carousel-item v-for="ad in advertisements" :key="ad.id">
          <img :src="ad.picture" :alt="ad.name" class="ad-image" url="ad.url">
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 分类导航 -->
    <div class="category-section">
      <h2>商品分类</h2>
      <el-row :gutter="20">
        <el-col :span="4" v-for="category in categories" :key="category.id">
          <div class="category-item" @click="navigateToCategory(category.url)">
            <div class="category-icon">{{ category.icon }}</div>
            <div class="category-name">{{ category.name }}</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 猜你喜欢 -->
    <div class="might-like-products">
      <div class="section-header">
        <h2><el-icon><Star /></el-icon> 猜你喜欢</h2>
        <el-button link @click="navigateToMore('mightLike')">查看更多</el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in mightLikeProducts" :key="product.id">
          <el-card :body-style="{ padding: '0px' }" class="product-card" @click="navigateToProduct(product.id)">
            <img :src="product.image" class="product-image">
            <div class="product-info">
              <h3 class="product-name-card">{{ product.name }}</h3>
              <div class="price">¥{{ product.price }}</div>
              <div class="store-sales">
                <span class="store-name">{{ product.storeName }}</span>
                <span class="sales">月销 {{ product.sold }}</span>
              </div>
              <el-button type="primary" size="small" @click.stop="handleAddToCart(product)">加入购物车</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 精选商品 -->
    <div class="featured-products">
      <div class="section-header">
        <h2><el-icon><Present /></el-icon> 精选商品</h2>
        <el-button link @click="navigateToMore('featured')">查看更多</el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in featuredProducts" :key="product.id">
          <el-card :body-style="{ padding: '0px' }" class="product-card" @click="navigateToProduct(product.id)">
            <img :src="product.image" class="product-image">
            <div class="product-info">
              <h3 class="product-name-card">{{ product.name }}</h3>
              <div class="price">¥{{ product.price }}</div>
              <div class="store-sales">
                <span class="store-name">{{ product.storeName }}</span>
                <span class="sales">月销 {{ product.sold }}</span>
              </div>
              <el-button type="primary" size="small" @click.stop="handleAddToCart(product)">加入购物车</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新品上市 -->
    <div class="new-products">
      <div class="section-header">
        <h2><el-icon><Timer /></el-icon> 新品上市</h2>
        <el-button link @click="navigateToMore('new')">查看更多</el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in newProducts" :key="product.id">
          <el-card :body-style="{ padding: '0px' }" class="product-card" @click="navigateToProduct(product.id)">
            <img :src="product.image" class="product-image">
            <div class="product-info">
              <h3 class="product-name-card">{{ product.name }}</h3>
              <div class="price">¥{{ product.price }}</div>
              <div class="store-sales">
                <span class="store-name">{{ product.storeName }}</span>
                <span class="sales">月销 {{ product.sold }}</span>
              </div>
              <el-button type="primary" size="small" @click.stop="handleAddToCart(product)">加入购物车</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

  </div>

  <!-- 页脚 -->
  <CommonFooter />
</template>

<style scoped>
/* 广告区域样式 */
.ad-section {
  margin: 20px auto 40px;
  max-width: 1600px;
}

.ad-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
  box-shadow: var(--el-box-shadow-light);
  transition: transform 0.3s ease;
}

.ad-image:hover {
  transform: scale(1.02);
}

:deep(.el-carousel__item) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  width: 44px;
  height: 44px;
  color: #fff;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}

:deep(.el-carousel__indicators) {
  bottom: -30px;
}

:deep(.el-carousel__button) {
  width: 30px;
  height: 3px;
  border-radius: 3px;
}

/* 调整主页容器样式 */
.home-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 轮播图样式优化 */
.banner {
  margin-bottom: 40px;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.category-section {
  margin-bottom: 40px;
}

.category-item {
  text-align: center;
  padding: 20px;
  background-color: var(--el-bg-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 20px;
}

.category-item:hover {
  transform: translateY(-5px);
  box-shadow: var(--el-box-shadow-lighter);
}

.category-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.category-name {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.might-like-products {
  margin-bottom: 40px;
}

.featured-products {
  margin-bottom: 40px;
}

.product-card {
  cursor: pointer;
  transition: all 0.3s;
  background-color: var(--el-bg-color);
  box-shadow: var(--el-box-shadow-light);
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--el-box-shadow-lighter);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 14px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.price {
  color: var(--el-color-danger);
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

h2 {
  font-size: 24px;
  color: var(--el-text-color-primary);
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-header h2 .el-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.new-products {
  margin-bottom: 40px;
}

.product-name-card {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.store-sales {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
  margin-bottom: 8px;
}

.store-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sales {
  margin-left: 10px;
}

.product-info .el-button {
  width: 100%;
}
</style>
